package com.duoec.doc.schedule;

import com.duoec.doc.dao.DocDao;
import com.duoec.doc.dao.DocLogDao;
import com.duoec.doc.doclet.pojo.Artifact;
import com.duoec.doc.doclet.pojo.entity.DocLog;
import com.duoec.doc.service.DocService;
import com.google.common.collect.Lists;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@Component
public class DocClearSchedule {
    public static final String STR_ID = "_id";
    public static final String STR_DOC_VERSION = "docVersion";
    public static final String STR_DOC_ID = "docId";

    /**
     * 需要保留的文档数， -1表示不自动清除
     */
    @Value("${duo.doc.history_count: -1}")
    private int docHistoryCount;

    @Autowired
    private DocDao docDao;

    @Autowired
    private DocLogDao docLogDao;

    @Autowired
    private DocService docService;

    @Scheduled(cron = "0 13 3 * * * ")
    public void clear() {
        if (docHistoryCount == -1) {
            return;
        }
        List<Artifact> docs = docDao.find()
                .projection(Projections.include(STR_ID))
                .into(Lists.newArrayList());
        docs.forEach((Consumer<? super Artifact>) this::clearDocHistory);
    }

    private void clearDocHistory(Artifact doc) {
        List<DocLog> list = docLogDao.find(Filters.eq(STR_DOC_ID, doc.getId()))
                .projection(Projections.include(STR_DOC_VERSION))
                .sort(Sorts.descending(STR_DOC_VERSION))
                .skip(docHistoryCount)
                .into(Lists.newArrayList());
        list.forEach((Consumer<? super DocLog>) docLog -> docService.delete(doc.getId(), docLog.getDocVersion()));
    }
}
